<template>
  <div class="toolBar">
    <div class="base">
      <ul>
        <li
          v-for="(item,index) in baseToolList"
          :key="'base'+index"
          :title="item.title"
          :style="{backgroundImage:'url('+item.imgUrl1+')'}"
          @click="toolClick(item.title)"
        ></li>
      </ul>
    </div>
    <div class="advanced">
      <ul>
        <li
          v-for="(item,index) in advancedToolList"
          :key="'advanced'+index"
          :title="item.title"
          :style="{backgroundImage:'url('+item.imgUrl1+')'}"
          @click="toolClick(item.title)"
        ></li>
      </ul>
    </div>
    <Draw v-if="drawToolVisiable" />

    <div class="search-input" v-if="isShowSearch">
      <el-autocomplete
        placeholder="请输入内容"
        v-model="searchValue"
        class="input-with-select"
        :fetch-suggestions="querySearch"
        :trigger-on-focus="false"
        @select="autocompleteSelect"
      >
        <el-select v-model="selectValue" slot="prepend" placeholder="请选择查询方式">
          <el-option label="坐标" value="position"></el-option>
          <el-option label="地名" value="address"></el-option>
        </el-select>
        <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
      </el-autocomplete>
    </div>
    <div v-if="isShowTianwafang" class="tianwafang">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>填挖方</span>
          <i class="el-icon-close" style="float:right;cursor: pointer" @click="closeTianwafang()"></i>
        </div>
        <div class="text item">
          <div class="content-item">
            <span>采样间距:</span>
            <input :value="twfInfo.jianju" />
          </div>
          <div class="content-item">
            <span>最高点:</span>
            <input :value="twfInfo.maxHeight.height" />
          </div>
          <div class="content-item">
            <span>最低点</span>
            <input :value="twfInfo.minHeight.height" />
          </div>
          <div class="content-item">
            <span>基准面高度(米):</span>
            <input :value="twfInfo.baseHeight" />
          </div>
          <div class="content-item">
            <span>填方体积(立方米):</span>
            <input :value="twfInfo.tianfangVolumn" />
          </div>
          <div class="content-item">
            <span>挖方体积(立方米):</span>
            <input :value="twfInfo.wafangVolumn" />
          </div>
          <div class="content-item">
            <span>填挖方总量(立方米)</span>
            <input :value="twfInfo.volumnSum" />
          </div>
          <div class="content-tool">
            <span>
              <button @click="drawTWF">标绘分析范围</button>
            </span>
            <span>
              <button id="analyze">分析</button>
            </span>
            <span>
              <button @click="clearTWF()">清除</button>
            </span>
          </div>
        </div>
      </el-card>
    </div>
    <div class="bottomImgs">
      <div v-for="(item,index)  in imgs" :key="index" >
        <img style="width:70px;height:70px;" :src="item" alt="">
        <div style="height:20px;"></div>
      </div>
    </div>
  </div>
</template>
<script>
import Draw from "@/pages/home/components/yanpan/draw.vue";
import axios from "axios";
import { TerrainToolCopy } from "@/cesiumPlugin/TerrainToolCopy.js";
import { PrimitivePoints } from "@/cesiumPlugin/PrimitivePoints.js";
const terrainProvider = new Cesium.CesiumTerrainProvider({
  url:
    "http://192.168.4.122:8310/tilecache/service/terrain/Global_DEM-TERRAIN-4326",
});
var twfPrimitive;
export default {
  name: "ToolBar",
  components: { Draw },
  computed: {
    // liStyle: function () {
    //   return {
    //     "--background-img": url(this.li.imgUrl),
    //     "--color-hover": url(this.li.imgUrl),
    //   };
    // },
  },
  data() {
    return {
      imgs:['./data/卫星4.png','./data/卫星1.png','./data/卫星2.png','./data/卫星3.png'],
      baseToolList: [
        { title: "放大", imgUrl1: "/data/toolBar/fangda.png" },
        { title: "缩小", imgUrl1: "/data/toolBar/suoxiao.png" },
      ],
      advancedToolList: [
        { title: "透明度", imgUrl1: "/data/toolBar/透明度1.png" },
        { title: "复位", imgUrl1: "/data/toolBar/复位.png" },
        { title: "搜索", imgUrl1: "/data/toolBar/搜索.png" },
        { title: "高程", imgUrl1: "/data/toolBar/高程.png" },
        { title: "等高线", imgUrl1: "/data/toolBar/等高线.png" },
        { title: "距离测量", imgUrl1: "/data/toolBar/距离.png" },
        { title: "面积测量", imgUrl1: "/data/toolBar/面积.png" },
        { title: "标绘", imgUrl1: "/data/toolBar/标绘.png" },
        { title: "淹没分析", imgUrl1: "/data/toolBar/淹没.png" },
        { title: "填挖方", imgUrl1: "/data/toolBar/填挖方.png" },
      ],
      isShowAltitude: false,
      isShowGaocheng: true,
      isShowYanmofenxi: false,
      drawToolVisiable: false,
      isShowSearch: false,
      addressPositionIndex: null,
      searchValue: null,
      selectValue: "position",
      addressPosition: [],
      isShowTianwafang: false,
      twfInfo: {
        jianju: 5,
        maxHeight: {},
        minHeight: {},
        baseHeight: null,
        tianfangVolumn: null,
        wafangVolumn: null,
        volumnSum: null,
      },
      drawEntity: null,
    };
  },
  methods: {
    toolClick(type) {
      switch (type) {
        case "放大":
          this.fangda();
          break;
        case "缩小":
          this.suoxiao();
          break;
        case "透明度":
          this.toumingdu();
          break;
        case "复位":
          this.fuwei();
          break;
        case "搜索":
          this.sousuo();
          break;
        case "高程":
          this.gaocheng();
        case "等高线":
          this.denggaoxian();
          break;
        case "距离测量":
          this.juliceliang();
          break;
        case "面积测量":
          this.mianjiceliang();
          break;
        case "标绘":
          this.biaohui();
          break;
        case "淹没分析":
          this.yanmofenxi();
          break;
        case "填挖方":
          this.tianwafang();
          break;
      }
    },
    fangda() {
      this.$cp.zoomIn();
    },
    suoxiao() {
      this.$cp.zoomOut();
    },
    toumingdu() {},
    fuwei() {
      this.$cp.reset();
    },
    sousuo() {
      this.isShowSearch = !this.isShowSearch;
    },
    gaocheng() {
      this.isShowGaocheng = !this.isShowGaocheng;
      this.$cp.showGaocheng(this.isShowGaocheng);
    },
    denggaoxian() {
      if (!this.isShowAltitude) {
        this.isShowAltitude = !this.isShowAltitude;
        var globe = this.$cp.viewer.scene.globe;

        globe.material = getCountorMaterial();
      } else {
        this.isShowAltitude = !this.isShowAltitude;
        var globe = this.$cp.viewer.scene.globe;
        globe.material = undefined;
      }
      function getCountorMaterial() {
        var material = Cesium.Material.fromType("ElevationContour");
        var contourUniforms = material.uniforms;
        contourUniforms.width = 2;
        contourUniforms.spacing = 150;
        contourUniforms.color = Cesium.Color.RED;

        return material;
      }
    },
    juliceliang() {
      this.$cp.juliceliang();
    },
    mianjiceliang() {
      this.$cp.mianjiceliang();
    },
    biaohui() {
      this.drawToolVisiable = !this.drawToolVisiable;
    },
    yanmofenxi() {
      this.isShowYanmofenxi = !this.isShowYanmofenxi;
      this.$cp.yanmofenxi(this.isShowYanmofenxi);
    },
    tianwafang() {
      this.isShowTianwafang = !this.isShowTianwafang;
    },
    autocompleteSelect(item) {
      this.addressPositionIndex = item.index;
    },
    querySearch(queryString, cb) {
      var that = this;
      if (this.selectValue === "address" && queryString) {
        let list = [];
        that.addressPosition = [];
        axios
          .get(
            "http://192.168.4.122:8310/placeservice/api/v1/query/placeName=" +
              queryString
          )
          .then((res) => {
            if (res.data.length > 0) {
              res.data.forEach((item, index) => {
                list.push({ value: item.DMMC, index: index });
                let strArr = item.wz.split(" ");
                that.addressPosition.push({
                  x: strArr[0].substring(6, strArr[0].length),
                  y: strArr[1].substring(0, strArr[1].length - 1),
                });
              });
            }

            cb(list);
          });
      } else {
        cb([]);
      }
    },
    search() {
      if (this.selectValue === "position") {
        let positionArr = this.searchValue.split(" ");

        this.$cp.viewer.scene.camera.flyTo({
          destination: Cesium.Cartesian3.fromDegrees(
            positionArr[0],
            positionArr[1],
            positionArr[2]
          ), //定位坐标点，建议使用谷歌地球坐标位置无偏差
          duration: 1, //定位的时间间隔
        });
      } else if (this.selectValue === "address") {
        this.$cp.viewer.scene.camera.flyTo({
          destination: Cesium.Cartesian3.fromDegrees(
            this.addressPosition[this.addressPositionIndex]["x"],
            this.addressPosition[this.addressPositionIndex]["y"],
            100000
          ), //定位坐标点，建议使用谷歌地球坐标位置无偏差
          duration: 1, //定位的时间间隔
        });
        // window.earth.iCamera.flyTo({
        //   lon: this.addressPosition["x"],
        //   lat: this.addressPosition["y"],
        //   alt: "131318.08141505756",
        //   heading: 360,
        //   pitch: -89.8770078029056,
        //   roll: 0
        // });
      }
    },
    closeTianwafang() {
      this.isShowTianwafang = false;
    },

    drawTWF() {
      var that = this;
      var viewer = this.$cp.viewer;
      var entityPolygon = null;
      viewer.scene.globe.depthTestAgainstTerrain = true;
      var tianfangArea = 0;
      var wafangArea = 0;
      var drawPoint = [];
      var points = null; //最后一个添加的点
      var activeShapePoints = []; //左键点击添加的点
      var activeShape; //绘制出的多边形
      var floatingPoint;
      var activePositionArr = [];
      function createPoint(worldPosition) {
        var point = viewer.entities.add({
          position: worldPosition,
          point: {
            pixelSize: 10,
            color: Cesium.Color.YELLOW,
            //disableDepthTestDistance: Number.POSITIVE_INFINITY,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
          },
        });
        points = point;
        drawPoint.push(point);
        return point;
      }
      function drawShape(positionData) {
        var shape;
        shape = viewer.entities.add({
          polygon: {
            hierarchy: [],
            material: new Cesium.ColorMaterialProperty(
              Cesium.Color.LIGHTSKYBLUE.withAlpha(0.7)
            ),
          },
        });
        shape.polygon.hierarchy = positionData;
        return shape;
      }
      var handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
      handler.setInputAction(function (event) {
        if (!Cesium.Entity.supportsPolylinesOnTerrain(viewer.scene)) {
          console.log("This browser does not support polylines on terrain.");
          return;
        }
        // 使用viewer.scene.pickPosition` 来代替`viewer.camera.pickEllipsoid` 这样当鼠标掠过terrain能得到正确的坐标
        var earthPosition = viewer.scene.pickPosition(event.position);
        activePositionArr.push(earthPosition);
        if (Cesium.defined(earthPosition)) {
          if (activeShapePoints.length == 0) {
            floatingPoint = createPoint(earthPosition);
            activeShapePoints.push(earthPosition);
            var dynamicPositions = new Cesium.CallbackProperty(function () {
              return new Cesium.PolygonHierarchy(activeShapePoints);
            }, false);
            activeShape = drawShape(dynamicPositions);
          }
          activeShapePoints.push(earthPosition);
          createPoint(earthPosition);
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

      handler.setInputAction(function (event) {
        if (Cesium.defined(floatingPoint)) {
          var newPosition = viewer.scene.pickPosition(event.endPosition);
          if (Cesium.defined(newPosition)) {
            floatingPoint.position.setValue(newPosition);
            activeShapePoints.pop();
            activeShapePoints.push(newPosition);
          }
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

      function terminateShape() {
        activeShapePoints.pop();
        for (let i = 0; i < drawPoint.length; i++) {
          viewer.entities.remove(drawPoint[i]);
        }
        if (that.drawEntity != null) {
          viewer.entities.remove(that.drawEntity);
        }
        entityPolygon = drawShape(activeShapePoints);
        that.drawEntity = entityPolygon;
        viewer.entities.remove(floatingPoint);
        viewer.entities.remove(activeShape);
        entityPolygon = null;
        floatingPoint = undefined;
        activeShape = undefined;
        activeShapePoints = [];
        handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
        handler.destroy();
        that.$message({
          message: "左键点击绘制面内一点获取基准面高度！",
        });
        var handler1 = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
        handler1.setInputAction(function (event) {
          if (!Cesium.Entity.supportsPolylinesOnTerrain(viewer.scene)) {
            console.log("This browser does not support polylines on terrain.");
            return;
          }
          // 使用viewer.scene.pickPosition` 来代替`viewer.camera.pickEllipsoid` 这样当鼠标掠过terrain能得到正确的坐标
          var earthPosition = viewer.scene.pickPosition(event.position);

          var cartographic = Cesium.Cartographic.fromCartesian(earthPosition);
          console.log(earthPosition);
          // Cesium.sampleTerrainMostDetailed(
          //   terrainProvider,
          //   [].concat(cartographic)
          // ).then(function (updatedPositions) {
          var height = cartographic.height;
          that.twfInfo.baseHeight = height;
          handler1.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
          handler1.destroy();
          // });
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
        handler.destroy();
      }

      handler.setInputAction(function (event) {
        terminateShape();
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

      document.getElementById("analyze").onclick = function () {
        viewer.entities.remove(that.drawEntity);
        let positionArr = [];
        let positionArr2 = []; //存储经纬度
        var ellipsoid = viewer.scene.globe.ellipsoid;
        for (let i = 0, len = activePositionArr.length; i < len; i++) {
          var cartographic = ellipsoid.cartesianToCartographic(
            activePositionArr[i]
          );
          var lat = Cesium.Math.toDegrees(cartographic.latitude);
          var lng = Cesium.Math.toDegrees(cartographic.longitude);

          positionArr.push(lng);
          positionArr.push(lat);
          let arrTmp = [];
          arrTmp.push(lng);
          arrTmp.push(lat);
          positionArr2.push(arrTmp);
        }
        positionArr2.push(positionArr2[0]);

        that.tianwafangjisuan(positionArr2, terrainProvider);
      };
      // $(".clearBtn").click(function() {
      //   viewer.entities.remove(that.drawEntity);
      //   that.drawEntity = null;
      //   for (let i = 0; i < drawPoint.length; i++) {
      //     viewer.entities.remove(drawPoint[i]);
      //   }
      //   that.tianfangArea = 0;
      //   that.waFangArea = 0;
      //   that.jizhunmian = 0;
      //   handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
      //   handler.destroy();
      // });
    },
    tianwafangjisuan(positionArr, terrain) {
      var that = this;
      let polygon = turf.polygon([positionArr]);
      //得到多边形面积
      let area = turf.area(polygon);
      //获取点间距
      let cellsize = (this.twfInfo.jianju = Math.sqrt(area / 100000));
      //获取外包矩形
      let enveloped = turf.envelope(polygon);
      //计算矩心
      let centroid = turf.centroid(polygon);
      //计算多边形边界
      let bbox = turf.bbox(enveloped);
      //获取点网格
      let grid = turf.pointGrid(bbox, cellsize, { units: "meters" });
      //查找属于多边形的点
      let ptsWithin = turf.pointsWithinPolygon(grid, polygon);

      let lonlats = [];

      let features = ptsWithin.features;
      for (let i = 0; i < features.length; i++) {
        lonlats.push({
          lon: features[i].geometry.coordinates[0],
          lat: features[i].geometry.coordinates[1],
        });
      }
      setTimeout(() => {
        TerrainToolCopy.LonlatPointsTerrainData(
          terrain,
          lonlats,
          (positions) => {
            getVolumn(positions);
          }
        );
      }, 0);

      function getVolumn(data) {
        let minHeightIndex = findMinHeight(data);
        let maxHeightIndex = findMaxHeight(data);
        that.twfInfo.minHeight.longitude = data[minHeightIndex].longitude;
        that.twfInfo.minHeight.latitude = data[minHeightIndex].latitude;
        that.twfInfo.minHeight.height = data[minHeightIndex].height;

        that.twfInfo.maxHeight.longitude = data[maxHeightIndex].longitude;
        that.twfInfo.maxHeight.latitude = data[maxHeightIndex].latitude;
        that.twfInfo.maxHeight.height = data[maxHeightIndex].height;

        let wafangVolumn = 0;
        let tianfangVolumn = 0;
        let points = [];
        let turfPoints = [];
        let tianfangPoints = [];
        let colors = [];
        var instances = [];
        for (var i = 0; i < data.length; i++) {
          if (data[i]["height"] > Number(that.twfInfo.baseHeight)) {
            //挖方
            wafangVolumn +=
              (data[i]["height"] - that.twfInfo.baseHeight) *
              cellsize *
              cellsize;

            let point = new Cesium.Cartesian3.fromRadians(
              data[i].longitude,
              data[i].latitude,
              data[i].height
            );
            points.push(point);
            colors.push(0.22);
            colors.push(0.37);
            colors.push(0.06);
            colors.push(1);
          } else {
            tianfangVolumn +=
              (that.twfInfo.baseHeight - data[i]["height"]) *
              cellsize *
              cellsize;
            let point = new Cesium.Cartesian3.fromRadians(
              data[i].longitude,
              data[i].latitude,
              data[i].height
            );

            points.push(point);
            colors.push(0);
            colors.push(0);
            colors.push(1);
            colors.push(1);
          }
        }
        twfPrimitive = new PrimitivePoints({
          viewer: window.viewer,
          Cartesians: points,
          Colors: colors,
        });

        that.twfInfo.wafangVolumn = wafangVolumn;
        that.twfInfo.tianfangVolumn = tianfangVolumn;
        that.twfInfo.volumnSum = wafangVolumn + tianfangVolumn;
      }

      function findMinHeight(e) {
        let minHeight = 5000000;
        let minPoint = null;
        let index = null;
        for (let i = 0; i < e.length; i++) {
          let height = e[i]["height"];
          let minDataIndex = i;
          if (height < minHeight) {
            minHeight = height;
            index = minDataIndex;
          }
        }
        return index;
      }
      function findMaxHeight(e) {
        let maxHeight = 0;
        let minPoint = null;
        let index = null;
        for (let i = 0; i < e.length; i++) {
          let height = e[i]["height"];
          let maxDataIndex = i;
          if (height > maxHeight) {
            maxHeight = height;
            index = maxDataIndex;
          }
        }
        return index;
      }
    },
    clearTWF() {
      twfPrimitive.remove();
      document.getElementById("analyze").onclick = null;
      this.twfInfo = {
        jianju: 5,
        maxHeight: {},
        minHeight: {},
        baseHeight: null,
        tianfangVolumn: null,
        wafangVolumn: null,
        volumnSum: null,
      };
    },
  },
};
</script>
<style lang="stylus">
@import '../../../assets/css/varibles.styl';

.toolBar {
  position: absolute;
  z-index: 9;
  right: vw(442);
  top: vh(29);

  ul {
    list-style: none;

    li {
      width: vh(36);
      height: vh(36);
      background-size: 100% 100%;
      cursor: pointer;
    }
  }

  .advanced {
    margin-top: vh(12);
  }

  .search-input {
    position: absolute;
    top: 0px;
    right: 59px;

    .el-input__inner {
      width: 180px;
    }

    .el-input-group__prepend {
      .el-select {
        width: 85px;
      }

      .el-input__inner {
        width: 85px;
      }
    }
  }

  .tianwafang {
    position: absolute;
    right: 50px;
    top: 0px;
    width: vw(390);

    .content-item {
      span {
        display: inline-block;
        width: vw(164);
        height: 30px;
      }

      input {
        border: 1px solid #d8d8d8;
        border-radius: 2px;
        height: 26px;
      }
    }

    .content-tool {
      float: right;
      margin-top: 15px;
      margin-bottom: 15px;

      button {
        width: 93px;
        height: 26px;
        background: #00abc6;
        border-radius: 4px;
        font-size: 12px;
        font-family: PingFangSC, PingFangSC-Regular;
        font-weight: 400;
        text-align: center;
        color: #ffffff;
        line-height: 17px;
        margin-right: 10px;
        border: none;
        cursor: pointer;
      }
    }
  }
  .bottomImgs{
    width:70px;
    backgroud:#fff;
    position:absolute;
    bottom:-550px;
    right:-10px;
    display:flex;
    flex-direction:column;

  }
}
</style>